<!-- src/views/outbound/fff/PackDialog.vue -->
<script setup>
import { ref } from 'vue';
import { packingApi } from '@/api/outbound/outboundOrderPackage';
import { ElMessage } from 'element-plus';

// 弹窗控制
const dialogVisible = ref(false);
const title = ref('打包操作');

// 表单数据
const packForm = ref({
  id: null,
  title: '',
  bePackNum: 0,
  packNum: 0
});

// 提交事件
const emit = defineEmits(['success']);

// 打开弹窗
const open = (row) => {
  packForm.value = {
    id: row.id,
    title: row.title,
    bePackNum: row.bePackNum,
    packNum: row.bePackNum // 默认填入待打包数量
  };
  dialogVisible.value = true;
};

// 关闭弹窗
const close = () => {
  dialogVisible.value = false;
};

// 处理打包操作
const handlePack = async () => {
  if (packForm.value.packNum <= 0) {
    ElMessage.warning('打包数量必须大于0');
    return;
  }
  
  if (packForm.value.packNum > packForm.value.bePackNum) {
    ElMessage.warning('打包数量不能超过待打包数量');
    return;
  }

  try {
    await packingApi(
      packForm.value.id,
      packForm.value.bePackNum,
      packForm.value.packNum
    );
    
    ElMessage.success('打包操作成功');
    dialogVisible.value = false;
    emit('success'); // 通知父组件打包成功
  } catch (error) {
    ElMessage.error('打包操作失败');
  }
};

// 暴露方法给外部调用
defineExpose({
  open,
  close
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
  >
    <el-form label-width="100px">
      <el-form-item label="商品名称">
        <el-input v-model="packForm.title" disabled />
      </el-form-item>
      <el-form-item label="待打包数量">
        <el-input v-model="packForm.bePackNum" disabled />
      </el-form-item>
      <el-form-item label="打包数量">
        <el-input-number 
          v-model="packForm.packNum" 
          :min="0" 
          :max="packForm.bePackNum"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handlePack">确认打包</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>